package org.aynu.parkingservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.aynu.parkingservice.common.ParkingResponse;
import org.aynu.parkingservice.entity.ParkingEntity;
import org.aynu.parkingservice.entity.ReserEntity;
import org.aynu.parkingservice.mapper.ParkingMapper;
import org.aynu.parkingservice.mapper.ReserMapper;
import org.aynu.parkingservice.service.ParkingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.aynu.parkingservice.common.ParkingStatusCode.*;

/**
 * 泊车服务设施
 *
 * @author 小粥
 * @since 2025/03/03
 */

@Service
@Slf4j
public class ParkingServiceImpl extends ServiceImpl<ParkingMapper, ParkingEntity> implements ParkingService {


    private final ReserMapper reserMapper;
    @Autowired
    public ParkingServiceImpl(ParkingMapper baseMapper, ReserMapper reserMapper) {
        this.reserMapper = reserMapper;
    }

    /**
     * 创建 Parking
     *
     * @param parkingEntity 停车实体
     * @return {@link ParkingResponse }<{@link Integer }>
     * @author 小粥
     * @since 2025/03/03
     */// 创建车位
    @Override
    public ParkingResponse<Integer> createParking(ParkingEntity parkingEntity) {
        try {
            // 确保 isDeleted 字段默认值为 0
            if (parkingEntity.getIsDeleted() == 0) {
                parkingEntity.setIsDeleted(0);
            }
            boolean result = this.save(parkingEntity);
            if (!result) {
                return ParkingResponse.error(CREATE_PARKING_FAILURE);
            }
            return ParkingResponse.success(CREATE_PARKING_SUCCESS, parkingEntity.getSpotId());
        } catch (Exception e) {
            log.error("创建车位时出现异常", e);
            return ParkingResponse.error(e);
        }
    }

    /**
     * 选择 Parking by ID （按 ID 停车）
     *
     * @param spotId Spot ID （点 ID）
     * @return {@link ParkingResponse }<{@link ParkingEntity }>
     * @author 小粥
     * @since 2025/03/03
     */// 通过 ID 查询车位信息
    @Override
    public ParkingResponse<ParkingEntity> selectParkingById(int spotId) {
        try {
            LambdaQueryWrapper<ParkingEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ParkingEntity::getSpotId, spotId)
                    .eq(ParkingEntity::getIsDeleted, 0); // 只查询未删除的车位
            ParkingEntity parkingEntity = this.getOne(queryWrapper);
            if (parkingEntity == null) {
                return ParkingResponse.error(PARKING_NOT_FOUND);
            }
            return ParkingResponse.success(PARKING_FOUND, parkingEntity);
        } catch (Exception e) {
            log.error("查询车位信息时出现异常", e);
            return ParkingResponse.error(e);
        }
    }

    /**
     * 选择停车位
     *
     * @return {@link ParkingResponse }<{@link List }<{@link ParkingEntity }>>
     * @author 小粥
     * @since 2025/03/03
     */// 查询所有车位
    @Override
    public ParkingResponse<List<ParkingEntity>> selectParking() {
        try {
            LambdaQueryWrapper<ParkingEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ParkingEntity::getIsDeleted, 0); // 只查询未删除的车位
            List<ParkingEntity> parkingList = this.list(queryWrapper);
            if (parkingList == null || parkingList.isEmpty()) {
                return ParkingResponse.error(PARKING_NOT_FOUND);
            }
            return ParkingResponse.success(PARKING_FOUND, parkingList);
        } catch (Exception e) {
            log.error("查询车位信息时出现异常", e);
            return ParkingResponse.error(e);
        }
    }

    /**
     * 选择按状态停车
     *
     * @return {@link ParkingResponse }<{@link List }<{@link ParkingEntity }>>
     * @author 小粥
     * @since 2025/03/03
     */// 查询可用车位
    @Override
    public ParkingResponse<List<ParkingEntity>> selectParkingByStatus() {
        try {
            LambdaQueryWrapper<ParkingEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ParkingEntity::getStatus, "可用") // 假设 ParkingStatus_available 是 "available"
                    .eq(ParkingEntity::getIsDeleted, 0); // 只查询未删除的车位
            List<ParkingEntity> parkingList = this.list(queryWrapper);
            if (parkingList == null || parkingList.isEmpty()) {
                return ParkingResponse.error(PARKING_NOT_FOUND);
            }
            return ParkingResponse.success(PARKING_FOUND, parkingList);
        } catch (Exception e) {
            log.error("查询可用车位时出现异常", e);
            return ParkingResponse.error(e);
        }
    }

    /**
     * 创建 ReserCreate ReserCreate Resers
     *
     * @param reserEntity reser 实体
     * @return {@link ParkingResponse }<{@link Integer }>
     * @author 小粥
     * @since 2025/03/03
     */// 预约车位
    @Override
    public ParkingResponse<Integer> createReser(ReserEntity reserEntity) {
        try {
            // 检查车位是否存在且状态为 available
            LambdaQueryWrapper<ParkingEntity> parkingQueryWrapper = new LambdaQueryWrapper<>();
            parkingQueryWrapper.eq(ParkingEntity::getSpotId, reserEntity.getSpotId())
                    .eq(ParkingEntity::getStatus, "可用")
                    .eq(ParkingEntity::getIsDeleted, 0);
            ParkingEntity parkingEntity = this.getOne(parkingQueryWrapper);
            if (parkingEntity == null) {
                return ParkingResponse.error(PARKING_ALREADY_RESERVED);
            }

            // 更新车位状态为 occupied
            LambdaUpdateWrapper<ParkingEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ParkingEntity::getSpotId, reserEntity.getSpotId())
                    .set(ParkingEntity::getStatus, "已占用"); // 假设 ParkingStatus_occupied 是 "occupied"
            boolean updateResult = this.update(updateWrapper);
            if (!updateResult) {
                return ParkingResponse.error(PARKING_ALREADY_RESERVED);
            }

            // 创建预约记录
            boolean insertResult = reserMapper.insert(reserEntity) > 0;
            if (!insertResult) {
                return ParkingResponse.error(PARKING_ALREADY_RESERVED);
            }

            return ParkingResponse.success(CREATE_RESERVATION_SUCCESS, reserEntity.getReservationId());
        } catch (Exception e) {
            log.error("创建预约记录时出现异常", e);
            return ParkingResponse.error(e);
        }
    }

    /**
     * 取消 Reser
     *
     * @param reservationsId 预订 ID
     * @param spotId         Spot ID （点 ID）
     * @return {@link ParkingResponse }<{@link Integer }>
     * @author 小粥
     * @since 2025/03/03
     */// 取消预约车位
    @Override
    public ParkingResponse<Integer> cancelReser(int reservationsId, int spotId) {
        try {
            // 检查预约记录是否存在
            LambdaQueryWrapper<ReserEntity> reserQueryWrapper = new LambdaQueryWrapper<>();
            reserQueryWrapper.eq(ReserEntity::getReservationId, reservationsId)
                    .eq(ReserEntity::getSpotId, spotId);
            ReserEntity reserEntity = reserMapper.selectOne(reserQueryWrapper);
            if (reserEntity == null) {
                return ParkingResponse.error(RESERVATION_NOT_FOUND);
            }

            // 更新车位状态为 available
            LambdaUpdateWrapper<ParkingEntity> parkingUpdateWrapper = new LambdaUpdateWrapper<>();
            parkingUpdateWrapper.eq(ParkingEntity::getSpotId, spotId)
                    .set(ParkingEntity::getStatus, "可用");
            boolean updateParkingResult = this.update(parkingUpdateWrapper);
            if (!updateParkingResult) {
                return ParkingResponse.error(RESERVATION_NOT_FOUND);
            }

            // 更新预约状态为 cancelled
            LambdaUpdateWrapper<ReserEntity> reserUpdateWrapper = new LambdaUpdateWrapper<>();
            reserUpdateWrapper.eq(ReserEntity::getReservationId, reservationsId)
                    .set(ReserEntity::getStatus, "已取消"); // 假设 ReserStatus_cancelled 是 "cancelled"
            boolean updateReserResult = reserMapper.update(null, reserUpdateWrapper) > 0;
            if (!updateReserResult) {
                return ParkingResponse.error(CANCEL_RESERVATION_FAILURE);
            }

            return ParkingResponse.success(CANCEL_RESERVATION_SUCCESS, reservationsId);
        } catch (Exception e) {
            log.error("取消预约记录时出现异常", e);
            return ParkingResponse.error(e);
        }
    }

    /**
     * 按 User ID 选择 reser
     *
     * @param userId 用户 ID
     * @return {@link ParkingResponse }<{@link List }<{@link ReserEntity }>>
     * @author 小粥
     * @since 2025/03/03
     */// 通过用户 ID 查询预约信息
    @Override
    public ParkingResponse<List<ReserEntity>> selectReserByUserId(int userId) {
        try {
            LambdaQueryWrapper<ReserEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ReserEntity::getUserId, userId);
            List<ReserEntity> reserList = reserMapper.selectList(queryWrapper);
            if (reserList == null || reserList.isEmpty()) {
                return ParkingResponse.error(RESERVATION_NOT_FOUND);
            }
            return ParkingResponse.success(PARKING_FOUND, reserList);
        } catch (Exception e) {
            log.error("查询预约信息时出现异常", e);
            return ParkingResponse.error(e);
        }
    }

    /**
     * 按 Spot ID 管理员更新停车位
     *
     * @param parkingEntity 停车实体
     * @return {@link ParkingResponse }<{@link Integer }>
     * @author 小粥
     * @since 2025/03/03
     */// 修改车位信息（管理员）
    @Override
    public ParkingResponse<Integer> updateParkingBySpotIdAdmin(ParkingEntity parkingEntity) {
        try {
            LambdaUpdateWrapper<ParkingEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ParkingEntity::getSpotId, parkingEntity.getSpotId())
                    .set(ParkingEntity::getSpotNumber, parkingEntity.getSpotNumber())
                    .set(ParkingEntity::getStatus, parkingEntity.getStatus())
                    .set(ParkingEntity::getLocation, parkingEntity.getLocation());
            boolean result = this.update(updateWrapper);
            if (!result) {
                return ParkingResponse.error(UPDATE_PARKING_FAILURE);
            }
            return ParkingResponse.success(UPDATE_PARKING_SUCCESS, parkingEntity.getSpotId());
        } catch (Exception e) {
            log.error("修改车位信息时出现异常", e);
            return ParkingResponse.error(e);
        }
    }

    /**
     * 按站点 ID 删除停车位
     *
     * @param spotId Spot ID （点 ID）
     * @return {@link ParkingResponse }<{@link Integer }>
     * @author 小粥
     * @since 2025/03/03
     */// 逻辑删除车位
    @Override
    public ParkingResponse<Integer> deleteParkingBySpotId(int spotId) {
        try {
            LambdaUpdateWrapper<ParkingEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ParkingEntity::getSpotId, spotId)
                    .set(ParkingEntity::getIsDeleted, 1);
            boolean result = this.update(updateWrapper);
            if (!result) {
                return ParkingResponse.error(DELETE_PARKING_FAILURE);
            }
            return ParkingResponse.success(DELETE_PARKING_SUCCESS, spotId);
        } catch (Exception e) {
            log.error("删除车位时出现异常", e);
            return ParkingResponse.error(e);
        }
    }
}